// ignore_for_file: prefer_const_constructors

import 'dart:async';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:multi_shop/services/auth_api.dart';
import 'package:multi_shop/services/user_api.dart';
import 'package:multi_shop/utils/index.dart';

class ForgotPasswordPage extends StatefulWidget {
  const ForgotPasswordPage({Key? key}) : super(key: key);

  @override
  State<ForgotPasswordPage> createState() => _ForgotPasswordPageState();
}

class _ForgotPasswordPageState extends State<ForgotPasswordPage> {
  final _formKey = GlobalKey<FormState>();

  final _emailCtrl = TextEditingController();
  final _codeCtrl = TextEditingController();
  final _pwdCtrl = TextEditingController();

  Timer? _timer;
  int _secLeft = 0;

  @override
  void dispose() {
    _timer?.cancel();
    _emailCtrl.dispose();
    _codeCtrl.dispose();
    _pwdCtrl.dispose();
    super.dispose();
  }

  // 发送验证码
  Future<void> _sendResetCode() async {
    if (!(_formKey.currentState?.validate() ?? false)) return;
    final email = _emailCtrl.text.trim();
    // 校验email

    // 校验email
    if (email.isEmpty || !RegExp(r'^[^@]+@[^@]+\.[^@]+').hasMatch(email)) {
      Get.snackbar('错误', '请输入有效的邮箱地址', snackPosition: SnackPosition.TOP);
      return;
    }

    try {
      await AuthApi().sendEmailCode(email, "find");
      await Future.delayed(const Duration(milliseconds: 400));
      Get.snackbar('提示', '验证码已发送至邮箱：$email', snackPosition: SnackPosition.TOP);
      _startCountdown(60);
    } catch (e) {
      Get.snackbar('错误', e.toString(), snackPosition: SnackPosition.TOP);
    }
  }

  void _startCountdown(int sec) {
    _timer?.cancel();
    setState(() => _secLeft = sec);
    _timer = Timer.periodic(const Duration(seconds: 1), (t) {
      if (_secLeft <= 1) {
        t.cancel();
        setState(() => _secLeft = 0);
      } else {
        setState(() => _secLeft--);
      }
    });
  }

  // 提交重置
  Future<void> _resetPassword() async {
    final email = _emailCtrl.text.trim();
    final code = _codeCtrl.text.trim();
    final pwd = _pwdCtrl.text;
    if (pwd.length < 6) {
      Get.snackbar('提示', '新密码至少 6 位', snackPosition: SnackPosition.TOP);
      return;
    }
    try {
      final newPwdSign = hmacSha256Hex(key: pwd, message: pwd);
      await UserApi().resetPassword(
        email: email,
        code: code,
        newPwd: newPwdSign,
      );
      await Future.delayed(const Duration(milliseconds: 500));
      Get.snackbar('成功', '密码已重置，请使用新密码登录', snackPosition: SnackPosition.TOP);
      Get.offAllNamed('/login');
    } catch (e) {
      // Get.snackbar('错误', e.toString(), snackPosition: SnackPosition.TOP);
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('忘记密码')),
      body: SafeArea(
        child: SingleChildScrollView(
          padding: EdgeInsets.all(24),
          child: Form(
            key: _formKey,
            child: Column(
              children: [
                Icon(
                  Icons.lock_open,
                  size: 72,
                  color: Theme.of(context).primaryColor,
                ),
                SizedBox(height: 16),
                Text(
                  '重置密码',
                  style: TextStyle(fontSize: 22, fontWeight: FontWeight.bold),
                ),

                SizedBox(height: 24),

                // 邮箱
                TextFormField(
                  controller: _emailCtrl,
                  keyboardType: TextInputType.emailAddress,
                  decoration: InputDecoration(
                    labelText: '邮箱',
                    prefixIcon: Icon(Icons.email),
                    border: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(8),
                    ),
                  ),
                  validator: (v) {
                    final s = v?.trim() ?? '';
                    if (s.isEmpty) return '请输入邮箱';
                    if (!GetUtils.isEmail(s)) return '请输入有效的邮箱地址';
                    return null;
                  },
                ),

                SizedBox(height: 16),

                // 验证码
                TextFormField(
                  controller: _codeCtrl,
                  keyboardType: TextInputType.number,
                  decoration: InputDecoration(
                    labelText: '验证码',
                    prefixIcon: Icon(Icons.verified),
                    border: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(8),
                    ),
                    suffixIcon: TextButton(
                      onPressed: _secLeft == 0 ? _sendResetCode : null,
                      child: Text(_secLeft == 0 ? '发送' : '$_secLeft s'),
                    ),
                  ),
                ),

                SizedBox(height: 16),

                // 新密码
                TextFormField(
                  controller: _pwdCtrl,
                  obscureText: true,
                  decoration: InputDecoration(
                    labelText: '新密码（≥6位）',
                    prefixIcon: Icon(Icons.lock),
                    border: OutlineInputBorder(
                      borderRadius: BorderRadius.circular(8),
                    ),
                  ),
                ),

                SizedBox(height: 24),

                SizedBox(
                  width: double.infinity,
                  height: 48,
                  child: ElevatedButton(
                    onPressed: _resetPassword,
                    style: ElevatedButton.styleFrom(
                      shape: RoundedRectangleBorder(
                        borderRadius: BorderRadius.circular(8),
                      ),
                    ),
                    child: Text('提交', style: TextStyle(fontSize: 16)),
                  ),
                ),

                SizedBox(height: 12),
                TextButton(onPressed: () => Get.back(), child: Text('返回登录')),
              ],
            ),
          ),
        ),
      ),
    );
  }
}
